import { queryEntity, createEntity, updateEntity, deleteEntity } from '../../services/api';

export default {
  namespace: 'systemRoleAuth',

  state: {
    apiUrl: '/system/auth',
    data: [],
    pagination: {
    },
    loading: true,
    selectItems: {
      authTypeSelectItems: [{ name: '目录', value: '目录' }, { name: '菜单', value: '菜单' }, { name: '操作', value: '操作' }]
    },
    userSelect: [],
  },

  effects: {
    *fetch({ payload }, { call, put, select }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(queryEntity, payload, '/system/auth');
      response.data.records.map(data => data['key'] = data.id);
      const r = {
        data: response.data.records,
        pagination: {
          total: response.data.total,
          pageSize: payload.pageSize,
          current: payload.current,
        },
      };
      yield put({
        type: 'save',
        payload: r,
      });
      yield put({
        type: 'changeLoading',
        payload: false,
      });
    },
    *add({ payload, callback }, { call, put, select }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(createEntity, payload, '/system/auth');
      if (callback) yield callback(response.code, response.message);
    },
    *edit({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(updateEntity, payload, '/system/auth');
      if (callback) yield callback(response.code, response.message);
    },
    *delete({ payload, callback }, { call, put }) {
      yield put({
        type: 'changeLoading',
        payload: true,
      });
      const response = yield call(removeSystemAuth, payload);
      if (callback) yield callback(response.code, response.message);
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        data: action.payload.data,
        pagination: action.payload.pagination,
      };
    },
    changeLoading(state, action) {
      return {
        ...state,
        loading: action.payload,
      };
    },
    saveSelectItems(state, action) {
      return {
        ...state,
        selectItems: {
          ...state.selectItems,
          ...action.payload,
        },
      }
    },
  },

};
